package com.saya.servlet;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.saya.model.User;
import com.saya.response.ResgisterRs;
import com.saya.utils.Utils;

@SuppressWarnings("serial")
public class RegisterServlet extends HttpServlet {
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("application/json;charset=utf8");
		Boolean validate = Boolean.valueOf(true);
		String des = "Bạn đã đăng ký thành công";
		String phoneNumber = req.getParameter("PhoneNumber");
		String deviceId = req.getParameter("DeviceId");
		String password = req.getParameter("Password");
		String email = req.getParameter("Email");
		String fullName = req.getParameter("FullName");

		if (!Utils.checkPhoneNumber(phoneNumber).booleanValue()) {
			validate = Boolean.valueOf(false);
			des = "Số điện thoại không hợp lệ";
		} else if (!Utils.checkEmail(email).booleanValue()) {
			validate = Boolean.valueOf(false);
			des = "Địa chỉ email không hợp lệ";
		}

		System.out.println(fullName);

		if (validate.booleanValue()) {
			User user = new User();
			user = user.getUser(phoneNumber);
			if (user != null) {
				validate = Boolean.valueOf(false);
				des = "Số điện thoại đã được đăng ký";
			} else {
				user = new User();
				user.setPhoneNumber(phoneNumber);
				user.setPassword(password);
				user.setFullName(fullName);
				user.setDeviceId(deviceId);
				user.setEmail(email);
				if (!user.CreateorUpdate(user).booleanValue()) {
					validate = Boolean.valueOf(false);
					des = "Có lỗi khi đăng ký";
				}
			}
		}
		ResgisterRs rs = new ResgisterRs();
		if (validate.booleanValue())
			rs.setCode("0");
		else {
			rs.setCode("1");
		}
		rs.setMessage(des);
		rs.setPhonenumber(phoneNumber);
		Gson gson = new Gson();

		resp.getWriter().println(gson.toJson(rs));
	}
}
